<template>
    <div>
        <div v-if="mode === 'DESIGN'">
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{ $t('module.select') }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'PC' && !readonly">
            <!--组件在PC端预览及真实显示的样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" readonly @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{ $t('module.select') }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'MOBILE' && !readonly">
            <!--组件在移动端预览及真实显示的样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" readonly @keyup.enter.native="show">
                <template #append>
                    <el-button @click="show">{{ $t('module.select') }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else>
            <!--组件在流程实例预览中，只读状态下样子-->
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" :disabled="readonly">
                <template #append>
                    <el-button :disabled="readonly" @click="show">{{ $t('module.select') }}</el-button>
                </template>
            </el-input>
        </div>
        <w-dialog :title="$t('module.selectData')" :okText="$t('webAuto.Submit')" :cancelText="$t('webAuto.cancel')" width="70%" style="height:600px;max-height:950px;overflow:hidden;"
                  v-model="visible"
                  @ok="httpOk" show-cancel-button>
            <div class="dialog">
                <el-input v-model="keywordSelect" style="width: 100%;margin-bottom: 5px;"
                          :placeholder="$t('module.keywordSearch')"
                          @change="search"/>
                <el-table :data="tableData" style="height: 90%;width: 100%" border v-loading="loading"
                          :header-cell-style="{ color: '#000', fontWeight: 'bold' }" highlight-current-row
                          @current-change="highlightCurrentChange2" :cell-style="{ whiteSpace: 'pre-wrap' }">
                    <template v-for="(item, index) in headerDate" >
                        <el-table-column v-if="item.placeholder" :key="index" :prop="item.value" :label="item.placeholder"
                                         width="auto"></el-table-column>
                    </template>
                </el-table>
                <div class="demo-pagination-block">
                    <el-pagination :currentPage="currentPage" :page-size="pageSize" :page-sizes="[20, 50, 80,120,200]"
                                   :small="small" :disabled="disabled" :background="background" pager-count="4"
                                   layout="total, sizes, prev, pager, next, jumper" :total="total"
                                   @size-change="handleSizeChange"
                                   @current-change="handleCurrentChange"/>
                </div>
            </div>
        </w-dialog>
    </div>

</template>

<script>
//混入配置
import componentMinxins from '../ComponentMinxins'
import store from '../../../../store/index'
import {reactive} from "vue";

export default {
    mixins: [componentMinxins],
    name: "Selector",
    components: {},
    props: {
        forms: {
            type: Array,
            default: () => {
                return []
            },
        },
        index: {
            type: Number,
            default: 0,
        },
        modelValue: {
            type: String,
            // default: () => {
            //     return []
            // }
        },
        placeholder: {
            type: String,
            default: 'webAuto.selectOption',
        },
        fixed: {
            type: Boolean,
            default: false
        },
        expanding: {
            type: Boolean,
            default: false,
        },
        dataSource: {
            type: String,
            default: '',
        },
        tables: {
            type: String,
            default: '',
        },
        options: {
            type: Array,
            default: () => {
                return []
            }
        },
        formData: {
            type: Object,
            default: () => {
                return {}
            }
        },
        http: {
            type: Object,
            default: () => {
                return {
                    url: null,
                    method: 'GET',
                    headers: [],
                    contentType: 'JSON',
                    params: [],
                    data: null,
                    preHandler: null,
                    aftHandler: {
                        isJs: false,
                        js: '',
                        rule: {
                            source: '',
                            name: '',
                            value: ''
                        }
                    },
                }
            }
        }
    },
    data() {
        return {
            loading: false,
            visible: false,
            keywordSelect: '',
            headerDate: [],
            tableData: [], // 表格绑定数据
            pageSize: 15, // 分页的
            total: 0,
            currentPage: 1,
            rowLis: {}, // 选择行的数据
            small: false,
            background: false,
            preHandlerFuc: null,
            aftHandlerFuc: null,
            disabled: false,
            lineNo: '',
        }
    },
    computed: {
        _value: {
            get() {
                return this.modelValue
            },
            set(val) {
                this.$emit('update:modelValue', val)
            },
        },
        formItems() {
            return this.$store.state.design.formItems
        },
        formMap() {
            const map = new Map();
            this.itemToMap(this.formItems, map)
            return map
        },
    },
    watch: {
        formData: {
            deep: true,
            handler() {
                // console.log('index变化了', this.index)
                this.doRequest()
                // 判断表格中是否有数据需要通过选择器里面的赋值，表格进行赋值操作
                let arr = []
                if (this.index == 0) {
                    // 判断表单中是否有表格
                    Object.values(this.formData).forEach(item => {
                        if (typeof item == 'object') {
                            item?.forEach(tableRow => {
                                if (Object.keys(tableRow)[0].indexOf("field") != -1) {
                                    arr = item
                                    // 赋值
                                    item.forEach(items => {
                                        // 选择的弹框数据存储到vuex
                                        this.options.forEach(m => {
                                            let a = m.name
                                            if (Object.keys(items)?.indexOf(a) != -1) {
                                                // 获取选择器里面的数据进行循环对吧
                                                let rowArr = store.state.formItem
                                                rowArr.forEach(row => {
                                                    //处理表格小数位赋值
                                                    if (Object.keys(row)?.length > 0 && Object.keys(row)?.indexOf(m.value) != -1) {
                                                        if (!items[a] || !row[m.value] || items[a] != row[m.value]) {
                                                            if (this.formMap.get(a)?.name &&
                                                                (this.formMap.get(a)?.name == 'NumberInput' || this.formMap.get(a)?.name == 'AmountInput' ||
                                                                    this.formMap.get(a)?.name == 'CalcFormula')) {
                                                                items[a] = Number(row[m.value]).toFixed(this.formMap.get(a).props?.precision)
                                                            } else {
                                                                items[a] = row[m.value]
                                                            }
                                                        }
                                                    }
                                                })
                                            }
                                        })
                                    })
                                }
                            })
                        }
                    })
                }
            }
        }
    },
    mounted() {
    },
    emits: ['update:modelValue'],
    methods: {
        doRequest() {
            this.headerDate = []
            if (this.http.url && this.http.method) {
                const params = {
                    url: this.http.url,
                    method: this.http.method.toLowerCase(),
                    headers: {
                        'Content-Type': this.http.contentType === 'JSON' ? 'application/json' : 'application/x-www-form-urlencoded',
                        'Wflowtoken':localStorage.getItem('wflow-token'),
                        ...this.coverParams(this.http.headers || [])
                    },
                    formData: Object.assign({}, this.formData),
                    params: this.coverParams(this.http.params || []), //查询条件
                    data: this.http.contentType === 'JSON' ? JSON.parse(this.bindVar(this.http.data || '{}')) : ''
                }
                params.params.value = this.keywordSelect   //表格自定义的查询条件 关键字查询
                params.params.pageSize = this.pageSize //分页 第几页
                params.params.pageNo = this.currentPage  //分页 每页条数
                this.preHandler(params, this.http.preHandler)
                //这里由于前置处理后，可能修改params参数，所以需要重新处理
                if (this.http.contentType !== 'JSON') {
                    params.data = this.coverParams(params.params, true)
                    params.params = {} //去除参数，防止参数跑到url中
                }
                this.loading = true
                this.$axios.request(params).then(rsp => {
                    // 接口返回数据赋值给表格，自定义处理了，就没有后置处理
                    // console.log(this.options)
                    // 循环比对表格表头
                    let arr = Object.keys(rsp.data.model)
                    this.options.forEach(item => {
                        arr.forEach(name => {
                            if (name === item.value) {
                                this.headerDate.push(item)
                            }
                        })
                    })
                    this.tableData = rsp.data.data
                    this.total = rsp.data.total
                    this.loading = false
                }).catch(err => {
                    this.loading = false
                    this.$message.warning(this.$t('webAuto.RequestSource') + JSON.stringify(err))
                })
            }
        },
        //前置处理
        preHandler(params, script) {
            if (!this.preHandlerFuc) {
                this.preHandlerFuc = new Function('ctx', `${script}\n preHandler(ctx)`)
            }
            try {
                this.preHandlerFuc(params)
            } catch (e) {
                // console.log(e)
            }
        },
        bindVar(str) {
            return str.replace(/\$\{(\w+)\}/g, (match, key) => {
                return this.formData[key] || '';
            })
        },
        //数组转对象
        coverParams(args, isForm = false) {
            let params = {};
            if (Array.isArray(args)) {
                args.forEach(arg => {
                    if (this.$isNotEmpty(arg.name)) {
                        params[arg.name] = arg.value.replace(/\$\{(\w+)\}/g, (match, key) => {
                            // 特殊处理 ${lang}
                            if (key === 'lang') {
                              return localStorage.getItem('lang')?.includes('中文') ? 'zh-CN' : localStorage.getItem('lang')?.includes('English')?'en-US':'es-MX';
                            }
                            return this.formData[key] || '';
                        })
                    }
                })
            } else {
                params = {...args}
            }
            if (isForm) {
                return Object.keys(params).map(v => `${v}=${params[v]}`).join('&')
            }
            return params
        },
        // 打开弹框
        show() {
            this.visible = true
            this.doRequest()
            this.keywordSelect = ''
        },
        itemToMap(forms, map) {
            forms?.forEach(item => {
                if (item.name === 'TableList') {
                    map.set(item.id, item)
                    this.itemToMap(item.props.columns, map)
                } else if (item.name === 'SpanLayout') {
                    this.itemToMap(item.props.items, map)
                } else {
                    map.set(item.id, item)
                }
            })
        },
        // 表格选择的时候
        highlightCurrentChange2(e) {
            // console.log(e)
            this.rowLis = e
        },
        // 弹框确定后的操作
        httpOk(r1) {
            // 点击确定后将选择的弹框表格数据存储到vuex,供后面表格使用
            if (store.state.formItem.length > 0) {
                store.state.formItem.forEach((item, index) => {
                    if (JSON.stringify(item) === JSON.stringify(this.rowLis)) {
                        // this.$message.warning('数据已选择')
                    } else {
                        store.commit('formItemAdd', this.rowLis)
                    }
                })
            } else {
                store.commit('formItemAdd', this.rowLis)
            }

            if (this.rowLis == null || Object.keys(this.rowLis).length == 0) {
                this.$message.warning(this.$t('webAuto.selectDataFirst'))
                return
            } else {
                this.lineNo = this.index
                // 点击确定后进行赋值
                let _this = this
                this.options.forEach(item => {
                    let a = item.name || ''
                    let arr = []
                    if (a) {
                        // 判断选择器是在表格里面还是外面
                        Object.values(this.formData).forEach(label => {
                            if (typeof label == 'object') {
                                // 表格里面列的循环
                                label.forEach(items => {
                                    if (Object.keys(items).indexOf(a) != -1) {
                                        let rowArr = store.state.formItem
                                        rowArr.forEach(row => {
                                            if (Object.keys(row).length > 0 && Object.keys(row).indexOf(item.value) != -1) { //判断选择的数据是否存在并且有没有绑定
                                                // 判断表格列是否添加过信息
                                                if (items[a]?.length > 0 && this.index - 1 > 0) {
                                                    label[this.index - 1][a] = this.rowLis[item.value]
                                                } else {
                                                    items[a] = row[item.value]
                                                }
                                            }
                                        })
                                    }
                                })
                            } else {
                                //处理表格小数位赋值
                                if (Object.keys(this.formData).indexOf(a) != -1) {
                                    if (this.formMap?.get(a)?.name &&
                                        (this.formMap?.get(a)?.name == 'NumberInput' || this.formMap?.get(a)?.name == 'AmountInput' ||
                                            this.formMap?.get(a)?.name == 'CalcFormula')) {
                                        this.formData[a] = Number(this.rowLis[item.value]).toFixed(this.formMap.get(a).props?.precision)
                                    } else {
                                        this.formData[a] = this.rowLis[item.value]
                                    }
                                }
                            }
                        })
                    }
                })
                this.visible = false
                this.rowLis = {}
            }
        },
        // 弹框里面表格的查询
        search() {
            this.doRequest()
        },
        // 分页相关函数
        handleSizeChange(val) {
            this.pageSize = val
            this.doRequest()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.doRequest()
        }
    }
}
</script>
<style scoped>
.demo-pagination-block {
    height: 40px;
    width: 100%;
    margin-top: 8px;
    box-sizing: border-box;
    font-size: 12px;
    background-color: #faf8f8;
    overflow: hidden;
}

.dialog {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 500px;
}

.el-select .el-select--default {
    width: 100px !important;
}

::v-deep .el-table__body tr.current-row > td {
    color: #fff;
    background: #4894c0 !important;
}
</style>
